﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using AzureDiagMon.Common.Interfaces;

namespace AzureDiagMon.Common.Services
{
    public abstract class BackgroundService : IService
    {
        Thread thread;
        protected object SyncRoot = new object();

        protected readonly ManualResetEvent StopManualResetEvent = new ManualResetEvent(false);

        protected abstract void Worker();
        protected virtual void SetupCulture()
        {
            //TODO: Do we need this?
            //Thread.CurrentThread.CurrentCulture = new CultureInfo("hu-HU");
            //Thread.CurrentThread.CurrentUICulture = new CultureInfo("hu-HU");
        }

        protected virtual void WorkerWrapper()
        {
            Trace.TraceInformation(String.Format("{0} started.", GetType().Name));
            Worker();
            Trace.TraceInformation(String.Format("{0} exited.", GetType().Name));
        }

        #region Implementation of IService

        public virtual void Start()
        {
            thread = new Thread(WorkerWrapper)
            {
                CurrentCulture = Thread.CurrentThread.CurrentCulture,
                CurrentUICulture = Thread.CurrentThread.CurrentUICulture
            };
            thread.Start();
        }

        public virtual void Stop()
        {
            StopManualResetEvent.Set();
        }

        #endregion
    }
}
